//
//  GMCoursePackageVC.m
//  Teecloud
//
//  Created by 小熊 on 2018/10/24.
//  Copyright © 2018年 小志. All rights reserved.
//

#import "GMCoursePackageVC.h"
#import "GMMyclassModel.h"
#import "GMBasePackageModel.h"
#import "XZCoursePackageCell.h"
#import "XZCoursePackageTitleCell.h"
#import "GMCommentVC.h"

#import "GMReadPDFVC.h"
#import "GMExercisesVC.h"
#import "GMExaminationVC.h"
#import "GMExamResultVC.h"
#import "GMPlayerViewController.h"
@interface GMCoursePackageVC ()<UITableViewDataSource,UITableViewDelegate>
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) GMBasePackageModel *model;
@property (nonatomic, strong) UIBarButtonItem *colectItem;
@property (nonatomic, strong) UIBarButtonItem *shareItem;
@property (nonatomic, strong) UIButton *colectBtn;

@end

@implementation GMCoursePackageVC


- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = self.titleStr;
    self.view.backgroundColor = kWhiteColor;
    _colectBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [_colectBtn addTarget:self action:@selector(conmmentAction) forControlEvents:UIControlEventTouchUpInside];
    [_colectBtn setImage:[UIImage imageNamed:@"comment"] forState:UIControlStateNormal];
    [_colectBtn sizeToFit];
    _colectItem = [[UIBarButtonItem alloc] initWithCustomView:_colectBtn];
    UIButton *shareBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [shareBtn addTarget:self action:@selector(shareBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [shareBtn setImage:[UIImage imageNamed:@"share_white"] forState:UIControlStateNormal];
    [shareBtn sizeToFit];
    _shareItem = [[UIBarButtonItem alloc] initWithCustomView:shareBtn];
    self.navigationItem.rightBarButtonItems  = @[self.shareItem,self.colectItem];
    [self.view addSubview:self.tableView];
    [self getData];
    [self addLeftBarButtonWithImage:[UIImage imageNamed:@"left-white-64"] action:@selector(left_BarButtonItemAction)];

}
- (void)left_BarButtonItemAction {
    if (kIsEmptyString(self.typeStr)) {
        [self.navigationController popViewControllerAnimated:YES];
    }else{
        [self.navigationController popToRootViewControllerAnimated:YES];
    }
}

#pragma mark - TableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 2;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        return self.model.FreeDatas.count;
    }else{
        return self.model.DirDatas.count;
    }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell ;
    if (indexPath.section == 0) {
        XZCoursePackageCell *packageCell = [tableView dequeueReusableCellWithIdentifier:@"XZCoursePackageCell"];
         GMMyclassModel *freeDatasModel = self.model.FreeDatas[indexPath.row];
        packageCell.model = freeDatasModel;
        cell = packageCell;
    }else{
        GMMyclassModel *dirDatasModel = self.model.DirDatas[indexPath.row];
        if (![dirDatasModel.DirGrade isEqualToNumber:@(1)]) {
            XZCoursePackageCell *packageCell = [tableView dequeueReusableCellWithIdentifier:@"XZCoursePackageCell"];
           
            packageCell.model = dirDatasModel;
            cell = packageCell;
        }else{
             XZCoursePackageTitleCell * titleCell = [tableView dequeueReusableCellWithIdentifier:@"XZCoursePackageTitleCell"];
            titleCell.model = dirDatasModel;
            cell = titleCell;
        }
    }
    return cell;
}
#pragma mark - TableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
          return 65.0f;
    }else{
        GMMyclassModel *dirDatasModel = self.model.DirDatas[indexPath.row];
        if (![dirDatasModel.DirGrade isEqualToNumber:@(1)]) {
            return 65.0f;
        }else{
            return 50.0f;
        }
    }
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:true];
    if (indexPath.section == 0) {
        GMMyclassModel *freeDatasModel = self.model.FreeDatas[indexPath.row];
        [self oneSectionSkipController:freeDatasModel];
    }else{
        GMMyclassModel *dirDatasModel = self.model.DirDatas[indexPath.row];
        if (![dirDatasModel.DirGrade isEqualToNumber:@(1)]) {
          [self skipController:dirDatasModel];
        }else{
            //id不等于null就做跳转
            if (dirDatasModel.Id != nil) {
              [self skipController:dirDatasModel];
            }
        }
        
    }
}

/**
 第一段点击的跳转

 @param model FreeDatas模型
 */
- (void)oneSectionSkipController:(GMMyclassModel *)model{
    /******************“考试”类资源类别的处理************************/
    //TestStatus=1，2：分别标注“进入考试”和“继续考试”，点击跳转到“我的资源 - 试卷考试 - 考试须知”页面
    if ([model.TestStatus isEqualToNumber:@(1)] || [model.TestStatus isEqualToNumber:@(2)]) {
        GMExaminationVC *exam = [[GMExaminationVC alloc] init];
        exam.resId = model.Id;
        exam.packId = self.resId;
        [self.navigationController pushViewController:exam animated:YES];
        return;
    }
    //TestStatus=9： PassMode>=0时点击跳转到“我的资源 - 试卷考试 - 答题卡 - 结果
    if ([model.TestStatus isEqualToNumber:@(9)]  && model.PassMode >= 0) {
        GMExamResultVC *examResultVC = [[GMExamResultVC alloc]init];
        examResultVC.examId = model.Id;
        [self.navigationController pushViewController:examResultVC animated:true];
        return;
    }
    //TestStatus=3：分别标注“停止入场”，无点击事件
    if ([model.TestStatus isEqualToNumber:@(3)]) {
        return;
    }
    
/*********************我的课件跳转一样****************************/
    if (model.NormalCode >0) {
        if (model.NormalCode ==1) {
            [MBProgressHUD showErrorOrSuc:@"关联资源已下架或不可用" toView:self.view];
        }else if (model.NormalCode ==2){
            [MBProgressHUD showErrorOrSuc:@"当前手机型 号非购买资源所用手机型号，你可以到“我的 - 主页 - 个人资料(付费资源管理)”模块申请变更手机型号。" toView:self.view];
        }else if (model.NormalCode ==3){
            [MBProgressHUD showErrorOrSuc:@"本期培训已结束，课件自动关闭；若有需要请报名参加下期培训。" toView:self.view];
        }
    }else{
        if ([model.ResType isEqualToNumber:@(1)]) {
            /**视频*/
            GMPlayerViewController *play = [[GMPlayerViewController alloc] init];
            play.resId = model.Id;
            play.packId = self.resId;
            [self.navigationController pushViewController:play animated:YES];
            
        }else if ([model.ResType isEqualToNumber:@(2)]){
            /**文档*/
            GMReadPDFVC *file = [[GMReadPDFVC alloc] init];
            file.packId = self.resId;
            file.resId = model.Id;
            [self.navigationController pushViewController:file animated:YES];
        }else if ([model.ResType isEqualToNumber:@(3)]){
            /**习题*/
            GMExercisesVC *exercises =[[GMExercisesVC alloc] init];
            exercises.resId = model.Id;
            exercises.packId = self.resId;
            [self.navigationController pushViewController:exercises animated:YES];
            
        }else if ([model.ResType isEqualToNumber:@(4)]){
            /**试卷*/
            GMExaminationVC *exam = [[GMExaminationVC alloc] init];
            exam.resId = model.Id;
            exam.packId = self.resId;
            [self.navigationController pushViewController:exam animated:YES];
            
        }else if ([model.ResType isEqualToNumber:@(9)]){
            /**课程包*/
            GMCoursePackageVC *package = [[GMCoursePackageVC alloc] init];
            package.resId = model.Id;
            package.titleStr = model.Name;
            [self.navigationController pushViewController:package animated:YES];
        }
    }
    
}

/**
 第二段的跳转

 @param model DirDatas模型
 */
- (void)skipController:(GMMyclassModel *)model{
    if (model.NormalCode >0) {
        if (model.NormalCode ==1) {
            [MBProgressHUD showErrorOrSuc:@"关联资源已下架或不可用" toView:self.view];
        }else if (model.NormalCode ==2){
            [MBProgressHUD showErrorOrSuc:@"当前手机型 号非购买资源所用手机型号，你可以到“我的 - 主页 - 个人资料(付费资源管理)”模块申请变更手机型号。" toView:self.view];
        }else if (model.NormalCode ==3){
            [MBProgressHUD showErrorOrSuc:@"本期培训已结束，课件自动关闭；若有需要请报名参加下期培训。" toView:self.view];
        }
    }else{
        if ([model.ResType isEqualToNumber:@(1)]) {
            /**视频*/
            GMPlayerViewController *play = [[GMPlayerViewController alloc] init];
            play.resId = model.Id;
            play.packId = self.resId;
            [self.navigationController pushViewController:play animated:YES];
            
        }else if ([model.ResType isEqualToNumber:@(2)]){
            /**文档*/
            GMReadPDFVC *file = [[GMReadPDFVC alloc] init];
            file.packId = self.resId;
            file.resId = model.Id;
            [self.navigationController pushViewController:file animated:YES];
        }else if ([model.ResType isEqualToNumber:@(3)]){
            /**习题*/
            GMExercisesVC *exercises =[[GMExercisesVC alloc] init];
            exercises.resId = model.Id;
            exercises.packId = self.resId;
            [self.navigationController pushViewController:exercises animated:YES];
            
        }else if ([model.ResType isEqualToNumber:@(4)]){
            /**试卷*/
            GMExaminationVC *exam = [[GMExaminationVC alloc] init];
            exam.resId = model.Id;
            exam.packId = self.resId;
            [self.navigationController pushViewController:exam animated:YES];
            
        }else if ([model.ResType isEqualToNumber:@(9)]){
            /**课程包*/
            GMCoursePackageVC *package = [[GMCoursePackageVC alloc] init];
            package.resId = model.Id;
            package.titleStr = model.Name;
            [self.navigationController pushViewController:package animated:YES];
        }
    }
}
#pragma mark - Setter
- (UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, DEVICE_WIDTH, DEVICE_HEIGHT-kNavBarAndStatusBarHeight-kBottomSafeHeight) style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.showsVerticalScrollIndicator =false;
        _tableView.separatorStyle =UITableViewCellSeparatorStyleNone;
        _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(getData)];
        //注册
        [_tableView registerNib:[UINib nibWithNibName:NSStringFromClass([XZCoursePackageTitleCell class]) bundle:nil] forCellReuseIdentifier:@"XZCoursePackageTitleCell"];
        [_tableView registerNib:[UINib nibWithNibName:NSStringFromClass([XZCoursePackageCell class]) bundle:nil] forCellReuseIdentifier:@"XZCoursePackageCell"];
        
    }
    return _tableView;
}
#pragma mark - Networking
- (void)getData{
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setValue:FROM_IOS forKey:@"from"];
    [dict setValue:[XGMArchiverTools cacheForKey:BUSIORGID] forKey:@"busiOrgId"];
    [dict setValue:[XGMArchiverTools cacheForKey:USER_UserId] forKey:@"userId"];
    [dict setValue:[XGMArchiverTools cacheForKey:USER_identifierNumber] forKey:@"loginFinger"];
    [dict setValue:self.resId forKey:@"resId"];
    [dict setValue:self.groupId forKey:@"groupId"];
    
    kWeakObject(self)
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [HJNetwork POSTWithURL:[NSString stringWithFormat:@"ajax-api.ashx?$c=TeeyunApp&$m=GetPackDetail&$v=%@",VERSION] parameters:dict cachePolicy:HJCachePolicyIgnoreCache callback:^(id responseObject, NSError *error) {
        [weakself.tableView.mj_header endRefreshing];
        [MBProgressHUD hideHUDForView:weakself.view animated:YES];
        if (!error) {
            if ([[responseObject objectForKey:RESULT_NAME_Success] boolValue]) {
                NSDictionary *dataInfo = [responseObject objectForKey:RESULT_NAME_Data];
                GMBasePackageModel *model = [GMBasePackageModel mj_objectWithKeyValues:dataInfo];
                weakself.model = model;
                if (model.DirDatas.count == 0 && model.FreeDatas.count == 0) {
                    [weakself.tableView setupEmptyDataText:@"暂无数据" secoundText:@"" buttonTit:@"" verticalOffset:0 emptyImage:NODATAIMG tapBlock:^{
                        
                    } butClick:^{
                        
                    }];
                }
                [weakself.tableView reloadData];
            }else{
                [MBProgressHUD showErrorOrSuc:[responseObject objectForKey:RESULT_NAME_Message] toView:weakself.view];
            }
        }else{
            [MBProgressHUD showErrorOrSuc:@"网络异常" toView:weakself.view];
        }
    }];
}

//分享
- (void)shareBtnClick{
    XZShareController *shareVC = [[XZShareController alloc] init];
    shareVC.shareTitle =self.titleStr;
    shareVC.shareContent = @"暂不支持课程包分享";
    shareVC.shareUrl =[NSString stringWithFormat:@"%@%@%@",URL_SERVER_HEADER,URL_SOFTWARE_SHARE,[XGMArchiverTools cacheForKey:USER_UserId]];
    shareVC.shareImgUrl = @"";
    shareVC.resId = self.resId;
    [self.navigationController presentSemiViewController:shareVC withOptions:@{
                                                                               KNSemiModalOptionKeys.pushParentBack    : @(NO),
                                                                               KNSemiModalOptionKeys.animationDuration : @(0.6),
                                                                               KNSemiModalOptionKeys.shadowOpacity     : @(0.3)
                                                                               }];
}
//评论
- (void)conmmentAction{
    GMCommentVC *comment = [[GMCommentVC alloc] init];
    comment.resId = self.resId;
    [self.navigationController pushViewController:comment animated:YES];
}
@end
